package com.qlk.vorder.service.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.perf4j.aop.Profiled;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qlk.common.utils.page.PageUtil;
import com.qlk.common.utils.wrap.WrapMapper;
import com.qlk.common.utils.wrap.Wrapper;
import com.qlk.vorder.domain.Orders;
import com.qlk.vorder.domain.enums.OrderCancelEnum;
import com.qlk.vorder.domain.enums.OrderCancelTypeEnum;
import com.qlk.vorder.domain.enums.OrderStatusEnum;
import com.qlk.vorder.domain.enums.PayStatusEnum;
import com.qlk.vorder.domain.enums.PayTypeEnum;
import com.qlk.vorder.domain.enums.SexEnum;
import com.qlk.vorder.domain.query.OrdersQuery;
import com.qlk.vorder.manager.OrdersManager;
import com.qlk.vorder.porxy.CreateRefundClient;
import com.qlk.vorder.porxy.QueryRefundProxy;
import com.qlk.vorder.porxy.dto.QueryRefundResponse;
import com.qlk.vorder.porxy.dto.RefundRequest;
import com.qlk.vorder.sdk.api.request.OrdersRequest;
import com.qlk.vorder.sdk.api.request.OrdersRequestDto;
import com.qlk.vorder.service.OrdersService;
import com.qlk.vorder.service.SerialLogService;
import com.qlk.vorder.utils.exceptions.Constant;
import com.qlk.vorder.utils.exceptions.ExistedException;

/**
 * OrdersService接口的实现类
 * 
 * @author zhaoyanan
 * @version 2016-7-28 14:14:00
 * 
 */
@Service
public class OrdersServiceImpl implements OrdersService {

	/** LOG */
	private static final Log LOG = LogFactory.getLog(OrdersServiceImpl.class);

	@Autowired
	private OrdersManager ordersManager;
	@Autowired
	private CreateRefundClient createRefundClient;

    @Autowired
    private QueryRefundProxy queryRefundProxy;
    
    @Autowired
    private SerialLogService serialLogService;

	/**
	 * {@inheritDoc}
	 */
	@Profiled(tag = "OrdersService.batchInsert")
	public boolean insert(List<Orders> ordersList) {
		boolean resultFlag = false;
		try {
			if (CollectionUtils.isNotEmpty(ordersList)) {
				resultFlag = ordersManager.insert(ordersList);
			} else {
				LOG.warn("OrdersServiceImpl#batchInsert failed, param is illegal.");
			}
		} catch (Exception e) {
			LOG.error("OrdersServiceImpl#batchInsert has error.", e);
		}
		return resultFlag;
	}

	/**
	 * {@inheritDoc}
	 */
	@Profiled(tag = "OrdersService.insert")
	public boolean insert(Orders orders) {
		boolean resultFlag = false;
		try {
			if (null != orders) {
				if (ordersManager.exist(orders)) {
					throw new ExistedException();
				}
				resultFlag = ordersManager.insert(orders);
			} else {
				LOG.warn("OrdersServiceImpl#insert failed, param is illegal.");
			}
		} catch (ExistedException e) {
			LOG.warn("OrdersServiceImpl#insert failed, orders has existed.");
			throw e;
		} catch (Exception e) {
			LOG.error("OrdersServiceImpl#insert has error.", e);
		}
		return resultFlag;
	}

	/**
	 * {@inheritDoc}
	 */
	@Profiled(tag = "OrdersService.update")
	public boolean update(Orders orders) {
		boolean resultFlag = false;
		try {
			if (null != orders && null != orders.getId()) {
				resultFlag = ordersManager.update(orders);
			} else {
				LOG.warn("OrdersServiceImpl#update failed, param is illegal.");
			}
		} catch (Exception e) {
			LOG.error("OrdersServiceImpl#update has error.", e);
		}
		return resultFlag;
	}

	/**
	 * {@inheritDoc}
	 */
	@Profiled(tag = "OrdersService.queryOrdersList")
	public List<Orders> queryOrdersList(OrdersQuery queryBean) {
		List<Orders> ordersList = null;
		try {
			ordersList = ordersManager.queryOrdersList(queryBean);
            fullFillOrderInfo(ordersList);
		} catch (Exception e) {
			LOG.error("OrdersServiceImpl#queryOrdersList has error.", e);
		}
		return ordersList;
	}

    /**
     * 填充订单信息
     * @param ordersList
     */
    private void fullFillOrderInfo(List<Orders> ordersList){

        if (CollectionUtils.isEmpty(ordersList)){
            return;
        }
        //            支付状态map
        Map<Integer, String> payStatusMap = PayStatusEnum.getMap();

//            订单状态map
        Map<Integer, String> orderStatusMap = OrderStatusEnum.getMap();

//            性别
        Map<Integer, String> sexMap = SexEnum.getMap();

        Map<Integer, String> orderCancelEnum = OrderCancelEnum.getMap();

//            支付方式
        Map<Integer, String> payTypeEnum = PayTypeEnum.getMap();

        Map<Integer, String> cancelTypeMap = OrderCancelTypeEnum.getMap();

        if (CollectionUtils.isNotEmpty(ordersList)){

            for (Orders order : ordersList){
                order.setOrderStatusName(orderStatusMap.get(order.getOrderStatus()));
                order.setPayStatusName(payStatusMap.get(order.getPayStatus()));
                order.setSexName(sexMap.get(order.getPatientSex()));
                order.setCancelDescribeName(orderCancelEnum.get(order.getCancelDescribe()));
//                    支付方式
                order.setPayWayName(payTypeEnum.get(order.getPayType()));
                order.setCancelTypeName(cancelTypeMap.get(order.getCancelType()));
            }
        }
    }

    public List<Orders> queryOrdersListForDownLoad(OrdersQuery queryBean) {
        List<Orders> ordersList = null;
        try {
            ordersList = ordersManager.queryOrdersList(queryBean);
            fullFillOrderInfo(ordersList);
        } catch (Exception e) {
            LOG.error("OrdersServiceImpl#queryOrdersListForDownLoad has error.", e);
        }
        return ordersList;
    }


	/**
	 * {@inheritDoc}
	 */
	@Profiled(tag = "OrdersService.queryOrdersListWithPage")
	public List<Orders> queryOrdersListWithPage(OrdersQuery queryBean, PageUtil pageUtil) {
		List<Orders> ordersList = null;
		try {
			ordersList = ordersManager.queryOrdersListWithPage(queryBean, pageUtil);
            fullFillOrderInfo(ordersList);
		} catch (Exception e) {
			LOG.error("OrdersServiceImpl#queryOrdersListWithPage has error.", e);
		}
		return ordersList;
	}

	/**
	 * {@inheritDoc}
	 */
	@Profiled(tag = "OrdersService.delete")
	public boolean delete(Orders orders) {
		boolean resultFlag = false;
		try {
			if (null != orders && null != orders.getId()) {
				resultFlag = ordersManager.delete(orders);
			} else {
				LOG.warn("OrdersServiceImpl#delete param is illegal.");
			}
		} catch (Exception e) {
			LOG.error("OrdersServiceImpl#delete has error.", e);
		}
		return resultFlag;
	}


    /**
     * 通过订单号查询退款信息
     * @param orderid
     * @return
     */
    public List<QueryRefundResponse> getRefundListByOrderid(String orderid){
        try {
            List<QueryRefundResponse> queryRefundResponseList = queryRefundProxy.getRefundListByOrderid(orderid);
            return queryRefundResponseList;
        }catch (Exception e){
            LOG.error("OrdersServiceImpl#getRefundListByOrderid has error.", e);
        }
        return null;
    }


	/**
	 * {@inheritDoc}
	 */
	@Profiled(tag = "OrdersService.batchDelete")
	public boolean delete(Orders[] orderss) {
		boolean resultFlag = false;
		try {
			if (null != orderss && orderss.length > 0) {
				resultFlag = ordersManager.delete(orderss);
			} else {
				LOG.warn("OrdersServiceImpl#batchDelete failed, param is illegal.");
			}
		} catch (Exception e) {
			LOG.error("OrdersServiceImpl#batchDelete has error.", e);
		}
		return resultFlag;
	}

	/**
	 * {@inheritDoc}
	 */
	@Profiled(tag = "OrdersService.getOrdersById")
	public Orders getOrdersById(Long id) {
		Orders orders = null;
		try {
			if (null != id) {
				orders = ordersManager.getOrdersById(id);
			} else {
				LOG.warn("OrdersServiceImpl#getOrdersById failed, param is illegal.");
			}
		} catch (Exception e) {
			LOG.error("OrdersServiceImpl#getOrdersById has error.", e);
		}
		return orders;
	}

	/**
	 * {@inheritDoc}
	 */
	@Profiled(tag = "OrdersService.getOrdersByOrderId")
	public Orders getOrdersByOrderId(OrdersQuery ordersQuery) {
		Orders orders = null;
		try {
			if (null != ordersQuery) {
				orders = ordersManager.getOrdersByOrderId(ordersQuery);
			} else {
				LOG.warn("OrdersServiceImpl#getOrdersByOrderId failed, param is illegal.");
			}
		} catch (Exception e) {
			LOG.error("OrdersServiceImpl#getOrdersByOrderId has error.", e);
		}
		return orders;
	}

	/**
	 * {@inheritDoc}
	 */
	@Profiled(tag = "OrdersService.innerData")
	public Wrapper<?> innerData(OrdersRequestDto request) {
		Wrapper<?> wrapper = null;
		try {
			wrapper = ordersManager.insertOrderData(request);
			return wrapper;
		} catch (RuntimeException e) {
			LOG.error("》》》创建虚拟订单异常《《《" + "" + e);
			return WrapMapper.error();
		} catch (Exception e) {
			LOG.error("OrdersServiceImpl#innerData has error.", e);
		}
		return WrapMapper.error();
	}

	/**
	 * {@inheritDoc}
	 */
	@Profiled(tag = "OrdersService.getBatchOrders")
	public List<Orders> getBatchOrders(OrdersRequest request) {
		List<Orders> ordersList = null;
		try {
			OrdersQuery queryBean = convertOrder(request);
			ordersList = ordersManager.queryOrdersList(queryBean);
		} catch (Exception e) {
			LOG.error("OrdersServiceImpl#queryOrdersList has error.", e);
		}
		return ordersList;
	}

	private OrdersQuery convertOrder(OrdersRequest request) {
		OrdersQuery ordersQuery = new OrdersQuery();
		List<String> list = Arrays.asList(request.getOrderids().split(","));
		ordersQuery.setOrderIds(list);
		ordersQuery.setOrderStatus(request.getOrderStatus());
		ordersQuery.setDrName(request.getDrName());
		ordersQuery.setDrId(request.getDrId());
		ordersQuery.setPatientName(request.getPatientName());
		ordersQuery.setPatientId(request.getPatientId());
		ordersQuery.setPatientMobile(request.getPatientMobile());
		ordersQuery.setPayStatus(request.getPayStatus());
		return ordersQuery;
	}

	/**
	 * {@inheritDoc}
	 */
	@Profiled(tag = "OrdersService.createRefundTask")
	public boolean createRefundTask(String keyword1) {
		boolean flag = false;
		List<Orders> ordersList = null;
		try {
			OrdersQuery queryBean = new OrdersQuery();
			queryBean.setOrderid(keyword1);
			ordersList = ordersManager.queryOrdersList(queryBean);
			if (CollectionUtils.isNotEmpty(ordersList)) {
				Orders orders = ordersList.get(0);
				RefundRequest refundRequest = convertRefund(orders);
				flag = createRefundClient.createRefund(refundRequest);
			}
		} catch (Exception e) {
			LOG.error("创建退款单异常", e);
		}
		return flag;
	}

	private RefundRequest convertRefund(Orders orders) {
		RefundRequest refundRequest = new RefundRequest();
		refundRequest.setOrder_id(orders.getOrderid());
		refundRequest.setRefund_mode(orders.getPayType());
		refundRequest.setUser_account(orders.getPatientId());
		refundRequest.setPlat_order_id(orders.getPayOrderSn());
		BigDecimal bd = new BigDecimal(orders.getOrderPrice());
		// 设置小数位数，第一个变量是小数位数，第二个变量是取舍方法(四舍五入)
		bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
		refundRequest.setRefund_money(bd);
		refundRequest.setCreate_user(Constant.SYSTEM_NAME);
		refundRequest.setReason(orders.getCancelDescribe());
		return refundRequest;
	}
}
